package com.AnywheeBt;

import com.AnywheeBt.R;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.AnywheeBt.PbapClient.utils.BTConfig;
import com.AnywheeBt.PbapClient.utils.StringUtils;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.bluetooth.BluetoothAdapter;
import android.os.SystemProperties;

import java.lang.Override;

public class BtSettings extends Activity {
	private Button mDuankaiBtn = null;
	private Button mXiugaiBtn = null;
	private Button mPinBtn = null;
	private Button mSettingBack = null;
	//
	private TextView mBtStatusTxt = null;
	private TextView mBtDevName = null;
	private TextView mPinNum = null;
	//
	private Button mAutoConBtn = null;
	private Button mAutoAnswerBtn = null;
    private BtStatusReceiver mBtStuReceiver = null;
    private BTApp mApp = null;
    private boolean bAutoConnect = true;
    private boolean bAutoAnswer = true;
    private BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();
    private String btMacStr = null;
	
	@Override
	protected void onResume() {
		bResume = true;
		if( SzhBAction.GetBtStartState() ) {
			SzhBAction.SetCmdBt(SzhBAction.AT_CMD_MM,0);
		}
		super.onResume();
	}
	
	@Override
	protected void onPause() {	
		bResume=false;	
		if(mEditDlg != null) mEditDlg.dismiss();
		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
                unregisterReceiver(mBtStuReceiver);
		super.onDestroy();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bt_settings);
        mApp = (BTApp)getApplication();
        bAutoConnect = mApp.isMbAutoConnect();
        bAutoAnswer = mApp.isMbAutoAnswer();
		
		mSettingBack = (Button) this.findViewById(R.id.setting_bt_back);
		mBtDevName = (TextView) this.findViewById(R.id.setting_bt_devicename);
		mBtStatusTxt = (TextView) this.findViewById(R.id.setting_bt_status);
		mPinNum =  (TextView) this.findViewById(R.id.setting_bt_pin_num);
		
		mDuankaiBtn = (Button) this.findViewById(R.id.setting_bt_duankai);
		mXiugaiBtn = (Button) this.findViewById(R.id.setting_bt_xiugai);
		mPinBtn = (Button) this.findViewById(R.id.setting_bt_pin);
		mAutoConBtn = (Button) this.findViewById(R.id.setting_bt_autoconnect);
		mAutoAnswerBtn = (Button) this.findViewById(R.id.setting_bt_autoanswer);
        Log.d("zcl","auto = " + bAutoConnect + " ,autoAns = " + bAutoAnswer);
        if(!bAutoConnect){
            mAutoConBtn.setBackground(getResources().getDrawable(R.drawable.off));
        }
        if(!bAutoAnswer){
            mAutoAnswerBtn.setBackground(getResources().getDrawable(R.drawable.off));
        }

                String bt_conn_statu = this.getIntent().getStringExtra("bt_conn_statu");
		if(StringUtils.toBool(bt_conn_statu)){
                    mBtStatusTxt.setText(getResources().getString(R.string.bt_connected)+SzhBAction.GetBtName());
                }else{
                    mBtStatusTxt.setText(R.string.bt_disconnected);
                }
		mBtStuReceiver = new BtStatusReceiver();
		IntentFilter intentFilter = new IntentFilter();  
                intentFilter.addAction(BTConfig.BT_CONNECTED);
                intentFilter.addAction(BTConfig.BT_DISCONNECTED); 
                registerReceiver(mBtStuReceiver, intentFilter);

//		OpenOrClose.setBackgroundResource(R.drawable.bohao_press);

		//BluetoothOnOff = (TextView) this.findViewById(R.id.bluetooth_on_off);
//		BluetoothOnOff.setText(R.string.bluetooth_openeds);
		
//		BtStateNames = (TextView) this.findViewById(R.id.bt_state_names);
//		BluetoothBack = (ImageView) this.findViewById(R.id.bluetooth_back);
//		BtStateNames.setText(R.string.msg_bt_no_connect);
        
        //获取蓝牙Mac地址
        if (mAdapter != null) {
          btMacStr = mAdapter.getAddress();  
         }
		mPinNum.setText(mApp.getmPinNum());
		mBtDevName.setText(SzhBAction.GetLocalBtName());
		if (mDuankaiBtn != null) {
			mDuankaiBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
//					OpenOrCloseBt();
					if (mAdapter.isEnabled()) {
						Log.d("zcl","bt state true = " + SzhBAction.GetBtState());
						mAdapter.disable();
					} else {
						mAdapter.enable();
						mAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE);
					}
				}
			});
		}
		
		if (mSettingBack != null) {
			mSettingBack.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					onBackPressed();
				}
			});
		}
		
		if (mBtDevName != null) {
			mBtDevName.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mBModifyName = true;
					BtDailog();
				}
			});
		}

        if (mPinNum != null) {
            mPinNum.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    mBModifyName = false;
                    BtDailog();
                }
            });
        }
		
		if (mAutoAnswerBtn != null) {
			mAutoAnswerBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
                  if(bAutoAnswer){
                      bAutoAnswer = false;
                      mApp.setProperty(BTApp.AUTO_ANSWER_STR, String.valueOf(bAutoAnswer));
                      mAutoAnswerBtn.setBackground(getResources().getDrawable(R.drawable.off));
                  }else{
                      bAutoAnswer = true;
                      mApp.setProperty(BTApp.AUTO_ANSWER_STR, String.valueOf(bAutoAnswer));
                      mAutoAnswerBtn.setBackground(getResources().getDrawable(R.drawable.kai));
                  }
				}
			});
		}		
		
		if (mAutoConBtn != null) {
			mAutoConBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
                  if(bAutoConnect){
                      bAutoConnect = false;
                      mApp.setProperty(BTApp.AUTO_CONNECT_STR, String.valueOf(bAutoConnect));
                      mAutoConBtn.setBackground(getResources().getDrawable(R.drawable.off));
                  }else{
                      bAutoConnect = true;
                      mApp.setProperty(BTApp.AUTO_CONNECT_STR, String.valueOf(bAutoConnect));
                      mAutoConBtn.setBackground(getResources().getDrawable(R.drawable.kai));
                  }
				}
			});
		}
		if(mXiugaiBtn != null){
			mXiugaiBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					mBModifyName = true;
					BtDailog();
				}
			});
		}
		if(mPinBtn != null){
			mPinBtn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					mBModifyName = false;
					BtDailog();
				}
			});
		}
		
	}

	protected void OpenOrCloseBt() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(BtSettings.this);
		boolean bState = prefs.getBoolean("bt_open", true);
		if (bState) {
			if (false == SzhBAction.GetBtStartState())return;
			if (isMyServiceRunning(BtSettings.this, "com.AnywheeBt.BTService")) {
				Intent msgIntent = new Intent(BtSettings.this, BTService.class);
				stopService(msgIntent);
			}
			prefs.edit().putBoolean("bt_open", false).commit();
//			ShowBtState(false);
// 			ShowBtName("");
			
			//OpenOrClose.setBackgroundResource(R.drawable.kaiguan);
	        Toast.makeText(BtSettings.this,getResources().getString(R.string.msg_bt_close),3).show();
	        //BluetoothOnOff.setText(R.string.bluetooth_closeds); 
		} else {
			if (SzhBAction.GetBtStartState())return;
			if (false == isMyServiceRunning(BtSettings.this,"com.AnywheeBt.BTService")) {
				Intent msgIntent = new Intent(BtSettings.this, BTService.class);
				startService(msgIntent);
			}
			prefs.edit().putBoolean("bt_open", true).commit();
			
			//OpenOrClose.setBackgroundResource(R.drawable.bohao_press);
			Toast.makeText(BtSettings.this,getResources().getString(R.string.msg_bt_open), 3).show();
			//BluetoothOnOff.setText(R.string.bluetooth_openeds);
			
		}
	}

//		void ShowBtState(boolean state) {
//    	BtStateNames.setText( state ? R.string.msg_bt_connect:R.string.msg_bt_no_connect);
//    	if (state==false) {
//    		BtStateNames.setText(R.string.msg_bt_no_connect);
//		}else {
//			BtStateNames.setText(R.string.msg_bt_connect);
//		}
//    }

	private boolean isMyServiceRunning(Context context, String ServiceName) {
		ActivityManager manager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if (ServiceName.equals(service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}

	private TextView mDlgTitleTxt = null;
	private TextView mEditTxt = null;
	private boolean bResume = false;
	private AlertDialog mEditDlg = null;
	private boolean mBModifyName = true;
	//
	public void BtDailog() {
		LayoutInflater factory = LayoutInflater.from(BtSettings.this);
		final View dlgview = factory.inflate(R.layout.customdialog, null);
		mDlgTitleTxt = (TextView) dlgview.findViewById(R.id.title);
		mEditTxt = (EditText) dlgview.findViewById(R.id.ed_btname);
		if(mBModifyName){
			mEditTxt.setText(SzhBAction.GetLocalBtName());
		}else{
			mEditTxt.setText(mPinNum.getText().toString().trim());
		}
		if(mBModifyName){
			mDlgTitleTxt.setText(R.string.title);
		}else{
			mDlgTitleTxt.setText(R.string.pin_title);
		}
		AlertDialog.Builder dlg_login = new AlertDialog.Builder(BtSettings.this);
		dlg_login.setView(dlgview);
		mEditDlg = dlg_login.create();
		mEditTxt.addTextChangedListener(new EditChangedListener());
		mEditDlg.show();
		((Button) dlgview.findViewById(R.id.confirm_btn)).setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						if(mBModifyName) {
							String strBtNme = mEditTxt.getText().toString().trim();
							if(TextUtils.isEmpty(strBtNme)){
								Toast.makeText(BtSettings.this, getResources().getString(R.string.msg_setting_error), 3).show();
								return;
							}else if (SzhBAction.GetBtStartState()) {
								Log.d("zcl","the btname is not null");
								SzhBAction.SetLocalBtName(strBtNme);
								mBtDevName.setText(SzhBAction.GetLocalBtName());
								Log.e("TAG", "ShowBtState" + strBtNme);

							}
							mEditDlg.dismiss();
							mBtDevName.setText(strBtNme);
						}else{
							String pinNum = mEditTxt.getText().toString().trim();
							if(TextUtils.isEmpty(pinNum)){
								Log.d("zcl","the pin is null");
								Toast.makeText(BtSettings.this, getResources().getString(R.string.msg_setting_error), 3).show();
								return;
							}else if(SzhBAction.GetBtStartState()){
								mApp.setmPinNum(pinNum);
								SystemProperties.set("persist.service.bdroid.pincode", pinNum);
							}
							mEditDlg.dismiss();
							mPinNum.setText(pinNum);
						}
					}
				});
		
		((Button) dlgview.findViewById(R.id.cancel_btn)).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mEditDlg.dismiss();
				
			}
		});
	}

	//
	void ShowBtName() {
		mBtDevName.setText(this.getResources().getString(R.string.msg_bt_name)+ SzhBAction.GetLocalBtName());
	}
        
        public class BtStatusReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if(action.equals(BTConfig.BT_CONNECTED)){
				mBtStatusTxt.setText(getResources().getString(R.string.bt_connected)+SzhBAction.GetBtName());
			}else if(action.equals(BTConfig.BT_DISCONNECTED)){
				mBtStatusTxt.setText(R.string.bt_disconnected);
			}
		}

	}
	
	//
	class EditChangedListener implements TextWatcher {
		
		@Override
		public void onTextChanged(CharSequence s, int start, int before,int count) {
		}
		
		@Override
		public void afterTextChanged(Editable s) {
			int editStart = mEditTxt.getSelectionStart();
			int editEnd = mEditTxt.getSelectionEnd();
			if (s.length() < 1)
				return;
			char ch = s.charAt(editStart - 1);
			if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z')
					|| (ch >= 'A' && ch <= 'Z') || ch == ':' || ch == '_' || ch == '-') {
				/*
				if (1 == s.length()) {
					char chStart = s.charAt(0);
					if (chStart >= '0' && chStart <= '9') {
						Toast.makeText(getApplicationContext(),
								getResources().getString(R.string.msg_bt_input_start_error), 3).show();
						s.delete(editStart - 1, editEnd);
					}
				}
				*/
				if (s.length() > 30) {
					Toast.makeText(getApplicationContext(),
							getResources().getString(R.string.msg_bt_input_num_error), 3).show();
					s.delete(editStart - 1, editEnd);
				}
			} else {
				Toast.makeText(getApplicationContext(),
						getResources().getString(R.string.msg_bt_input_error),3).show();
				s.delete(editStart - 1, editEnd);
			}
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,int after) {
			
		};
	}
}
